# -*- coding: utf-8 -*-

from odoo import models, fields, api


class CpqProject(models.Model):
    _name = 'cpq.project'
    _description = '项目'
    _rec_name = 'name'
    _order = 'create_date desc'

    # 基础信息
    name = fields.Char('项目名称', required=True, index=True)
    code = fields.Char('项目编号', required=True, index=True, help='如：MS11, T167')
    
    # 客户信息
    partner_id = fields.Many2one(
        'cpq.partner',
        '客户',
        required=True,
        domain=[('partner_type', 'in', ['customer', 'both'])],
        help='客户公司'
    )
    
    # 项目信息
    vehicle_model = fields.Char('车型', help='如：奔驰E级、小米SU7')
    estimated_quantity = fields.Float(
        '预计产量',
        digits=(16, 0),
        help='预计总产量（件）'
    )
    annual_quantity = fields.Float(
        '年度产量',
        digits=(16, 0),
        help='年度产量（件/年）'
    )
    lifecycle_years = fields.Integer('生命周期（年）', default=5)
    
    # 时间节点
    sop_date = fields.Date('SOP日期', help='Start of Production')
    bidding_date = fields.Date('竞标日期')
    create_date = fields.Datetime('创建日期', readonly=True)
    
    # 状态
    state = fields.Selection([
        ('draft', '草稿'),
        ('bidding', '竞标中'),
        ('won', '中标'),
        ('lost', '未中标'),
        ('sop', 'SOP'),
        ('closed', '关闭')
    ], string='状态', default='draft', index=True)
    
    # BOM版本
    bom_ids = fields.One2many('cpq.bom', 'project_id', 'BOM版本')
    bom_count = fields.Integer('BOM版本数', compute='_compute_bom_count', store=True)
    
    # 当前版本
    current_l1_bom_id = fields.Many2one(
        'cpq.bom',
        '当前L1版本',
        compute='_compute_current_bom',
        store=False
    )
    current_l2_bom_id = fields.Many2one(
        'cpq.bom',
        '当前L2版本',
        compute='_compute_current_bom',
        store=False
    )
    current_l3_bom_id = fields.Many2one(
        'cpq.bom',
        '当前L3版本',
        compute='_compute_current_bom',
        store=False
    )
    
    # 货币
    currency_id = fields.Many2one(
        'cpq.currency',
        '货币',
        default=lambda self: self._get_default_currency()
    )
    
    @api.model
    def _get_default_currency(self):
        """获取默认货币（人民币）"""
        currency = self.env['cpq.currency'].search([('code', '=', 'CNY')], limit=1)
        if not currency:
            # 如果没有人民币，返回第一个货币
            currency = self.env['cpq.currency'].search([], limit=1)
        return currency.id if currency else False
    
    # 备注
    notes = fields.Text('备注')
    
    @api.depends('bom_ids')
    def _compute_bom_count(self):
        for record in self:
            record.bom_count = len(record.bom_ids)
    
    @api.depends('bom_ids', 'bom_ids.version_type', 'bom_ids.state')
    def _compute_current_bom(self):
        for record in self:
            # 查找当前有效的L1版本
            l1_bom = record.bom_ids.filtered(
                lambda b: b.version_type == 'l1' and b.state != 'cancelled'
            ).sorted('create_date', reverse=True)
            record.current_l1_bom_id = l1_bom[0] if l1_bom else False
            
            # 查找当前有效的L2版本（已锁定）
            l2_bom = record.bom_ids.filtered(
                lambda b: b.version_type == 'l2' and b.state == 'locked'
            ).sorted('create_date', reverse=True)
            record.current_l2_bom_id = l2_bom[0] if l2_bom else False
            
            # 查找当前有效的L3版本
            l3_bom = record.bom_ids.filtered(
                lambda b: b.version_type == 'l3' and b.state != 'cancelled'
            ).sorted('create_date', reverse=True)
            record.current_l3_bom_id = l3_bom[0] if l3_bom else False
    
    @api.model
    def create(self, vals):
        # 自动生成项目编号（如果未提供）
        if not vals.get('code') and vals.get('name'):
            # 从名称提取编号，或使用默认格式
            name = vals.get('name', '')
            # 尝试提取编号（如"MS11项目" -> "MS11"）
            import re
            match = re.search(r'([A-Z]+\d+)', name.upper())
            if match:
                vals['code'] = match.group(1)
            else:
                # 使用默认格式：PRJ + 序号
                last_project = self.search([], order='id desc', limit=1)
                next_num = (last_project.id + 1) if last_project else 1
                vals['code'] = f'PRJ{next_num:04d}'
        return super().create(vals)
    
    def name_get(self):
        result = []
        for record in self:
            name = f'[{record.code}] {record.name}' if record.code else record.name
            result.append((record.id, name))
        return result
    
    def action_confirm(self):
        """确认项目"""
        self.write({'state': 'bidding'})
        return True
    
    def action_bidding(self):
        """开始竞标"""
        self.write({'state': 'bidding'})
        return True

